package com.sushi.bigblog.filedb;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

/**
 * User: bianpeng
 * Date: 11-12-19
 */
class LazyDbEntry {
    public static final int VERSION_LENGTH = 4; // 4字节,一个整数的版本号

    private RandomAccessFile file;
    private List<DbEntry> entries;

    public LazyDbEntry(RandomAccessFile file) throws IOException {
        // entry file
        this.file = file;
        // entry
        int len = (int) (file.length() - VERSION_LENGTH);
        assert len % DbEntry.ENTRY_LENGTH == 0;
        int n = len / DbEntry.ENTRY_LENGTH;
        entries = new ArrayList<DbEntry>(n*2);
        for(int i = 0; i < n; ++i) entries.add(null);
    }

    public DbEntry getEntry(int idx) throws IOException {
        if (idx < 0 || idx >= entries.size()) return null;
        DbEntry entry = entries.get(idx);
        if (entry != null) return entry;
        file.seek(VERSION_LENGTH + idx * DbEntry.ENTRY_LENGTH);
        entry = DbEntry.load(file);
        entries.set(idx, entry);
        return entry;
    }

    public void addEntry(DbEntry entry) throws IOException {
        entries.add(entry);
        int len = (int) file.length();
        assert (len - VERSION_LENGTH) % DbEntry.ENTRY_LENGTH == 0;   // 4字节是版本号
        file.seek(len);
        DbEntry.save(file, entry);
    }

    public DbEntry findEntry(long offset) throws IOException {
        int n = entries.size();
        while(n >= 0) {
            DbEntry entry = getEntry(n - 1);
            if (entry.getOffset() == offset) return entry;
            --n;
        }
        return null;
    }

    public List<DbEntry> getEntryList(int offset, int limit) throws IOException {
        List<DbEntry> result = new ArrayList<DbEntry>(limit);
        int min = Math.max(0, entries.size() - limit);
        for(int i = entries.size() - offset - 1; i >= min; --i) {
            result.add(getEntry(i));
        }
        return result;
    }
}
